package com.sto.stoapp.activity.scanner;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.dataprocess.ProcessScanCode;
import com.sto.stoapp.dataprocess.parcelable.GetTableParcel;
import com.sto.stoapp.dataprocess.parcelable.SelectTableParcel;
import com.sto.stoapp.db.StoDataBaseOperation;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.manager.SqlSelectTableManager;
import com.sto.stoapp.entity.BillPaymentEntity;
import com.sto.stoapp.entity.DataBusinessEntity;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.manager.BlueWeigthManager;
import com.sto.stoapp.status.EnumScanCode;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.thread.BlueReadThread;
import com.sto.stoapp.thread.HelpGetPaymentThread;
import com.sto.stoapp.util.BillFilterUtil;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.widget.BaseDialog;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoHhmEditText.EditClickListener;
import com.sto.stoapp.widget.StoListenerActivity;

import java.util.ArrayList;
import java.util.List;
@SuppressLint("HandlerLeak")
public class StoScanAssignPieceActivity extends StoListenerActivity {

	private StoHhmEditText assignPerson;
	// private StoHhmEditText code;
	private DataBusinessEntity dataBusiness;

	private List<EditText> edit = new ArrayList<EditText>();

	private final int COURIER_RESULT = 0xfe;
	// private int count = 0;

	private String assignCode = "", assignName = "";

	private TextView weight;
	private float blueWeight = -1;
	private String billNo="";
	private BaseDialog filterDialog=null;

	private Handler mHandler=new Handler(){
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what){
				case HelpGetPaymentThread.MSG_WHAT:

					Helper.showWaitePaySound(StoScanAssignPieceActivity.this);
					BillPaymentEntity entity= (BillPaymentEntity) msg.obj;

					ScanOff();
					final BaseDialog filterDialog=new BaseDialog(StoScanAssignPieceActivity.this);
					filterDialog.setTitles("此单号【" + entity.getBillNo() + "】为代收货款单号，代收金额为：【￥"+Double.valueOf(entity.getBillPayment())+"】。请注意代收！");
					filterDialog.show();
					filterDialog.getvCanncel().setVisibility(View.GONE);
					filterDialog.getvAccept().setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							filterDialog.dismiss();
							ScanOpen();
						}
					});
					break;
			}

			super.handleMessage(msg);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sto_scanning_assign_piece);
		this.setTitleBottom(R.string.assign_piece,
				HomeBroadAction.SCANNER_MAN_BROAD);

		dataBusiness = new DataBusinessEntity();
		dataBusiness.initInsertData();
		initPointLayout(true);
		initWidget();
		initListen();
		initScanListener();
		initScanRecordAdapter(EnumTableNames.STATUS_TABLE_SCANNING_ASSIGNPIECE);
		bluetoothConnect();
	}

	/*
	 * 初始化控件
	 */
	private void initWidget() {
		assignPerson = (StoHhmEditText) this
				.findViewById(R.id.sanning_assign_person);
		code = (StoHhmEditText) this.findViewById(R.id.sanning_code);
		weight = (TextView) this.findViewById(R.id.enter_count);
		edit.add(assignPerson);
		edit.add(code);
		addUploadTable(EnumTableNames.STATUS_TABLE_SCANNING_ASSIGNPIECE);
	}

	/**
	 * 选择列表返回的结果
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == COURIER_RESULT && resultCode == RESULT_OK) {
			GetTableParcel courierEntity = data.getParcelableExtra("Name");
			if (courierEntity != null) {
				assignPerson.setText(courierEntity.getSelectName());
				assignPerson.setSelection(assignPerson.length());
				assignCode = courierEntity.getSelectCode();
			}
			if (assignCode.length() > 0)
				assignName = courierEntity.getSelectName();
			code.requestFocus();
		} else if (requestCode == COURIER_RESULT
				&& resultCode == RESULT_FIRST_USER) {
			assignPerson.setText("");
			assignName = "";
			Helper.showSoundToast(StoScanAssignPieceActivity.this,
					getString(R.string.undefined), false);
		}
	}

	// 处理扫描数据
	@SuppressLint("NewApi")
	private void processScanData() {
		try {

			if (!weight.getText().toString().isEmpty() && blueWeight <= 0) {
				Helper.showSoundToast(this, getString(R.string.no_weight_data),
						false);
				return;
			}

			if (!assignName.equals(assignPerson.getText().toString())) {
				Helper.showSoundToast(this, "请选择正确的派件员", false);
				assignPerson.requestFocus();
				assignPerson.setText("");
				return;
			}
			if (!assignCode.isEmpty() && !code.getText().toString().isEmpty()) {

				billNo=code.getText().toString();

				//Add by wj过滤单号
				boolean isFilter= BillFilterUtil.isFilter(billNo,this);
				if(isFilter){
					showFilterDialog(code.getText().toString().trim());
					return;
				}

				float maxWeight=StoFilePreference.getInstance(this).getBlueWeight();
				if(blueWeight>maxWeight){
					ScanOff();
					filterDialog=new BaseDialog(this);
					filterDialog.setTitles("重量限制为【" + maxWeight + "】\n当前重量为【" + blueWeight + "】\n请确认重量是否准确");
					filterDialog.show();
					filterDialog.getvCanncel().setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							filterDialog.dismiss();
							ScanOpen();
						}
					});
					filterDialog.getvAccept().setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							filterDialog.dismiss();

							//End by wj
							//代收货款校验
							//代收货款校验
							int onOff=StoFilePreference.getInstance(StoScanAssignPieceActivity.this).getPayMentOnOff();
							if(1==onOff){
								if("11".equals(billNo.substring(0,2)) || "33".equals(billNo.substring(0,2))){
									new HelpGetPaymentThread(billNo,StoScanAssignPieceActivity.this,mHandler).start();
								}
							}


							//代收货款校验
							if (addPieceRecord(billNo)) {
								addCodeNumber();
								setSaveData(true);
								// SoundManager.getInstance(this).playSuccessSound();
								Helper.showSoundAndVibrator(StoScanAssignPieceActivity.this, true);
								code.setSelection(code.length());
								addScanRecordInfo(billNo,weight.getText().toString());
								code.setText("");
							}
							// 提示插入数据失败
							else {
								Helper.showSoundToast(StoScanAssignPieceActivity.this,
										getString(R.string.code_repeat), false);
							}
							ScanOpen();
						}
					});
				}else {
					//End by wj
					//代收货款校验
					//代收货款校验
					int onOff=StoFilePreference.getInstance(this).getPayMentOnOff();
					if(1==onOff){
						String bill=code.getText().toString().trim();
						if("11".equals(bill.substring(0,2)) || "33".equals(bill.substring(0,2))){
							new HelpGetPaymentThread(bill,StoScanAssignPieceActivity.this,mHandler).start();
						}
					}
					//代收货款校验
					if (addPieceRecord(billNo)) {
						this.addCodeNumber();
						setSaveData(true);
						// SoundManager.getInstance(this).playSuccessSound();
						Helper.showSoundAndVibrator(this, true);
						code.setSelection(code.length());
						addScanRecordInfo(code.getText().toString(),weight
								.getText().toString());
						code.setText("");
					}
					// 提示插入数据失败
					else {
						Helper.showSoundToast(this,
								getString(R.string.code_repeat), false);
					}
					ScanOpen();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("processScanData", e.getMessage());
		}
	}

	// 增加一条记录
	private boolean addPieceRecord(String billNo) {
		boolean ret;

		// 扫描类型
		dataBusiness.setCommand_type(EnumTableNames.STATUS_TABLE_SCANNING_ASSIGNPIECE.getOpCode());
		// 单号
		dataBusiness.setBar_code_number(billNo);
		
		dataBusiness.setCodeType(getExpType(billNo));
		// 派件员
		dataBusiness.setNext_station(assignCode);
		// 派件员名称
		dataBusiness.setUser_defined3(assignPerson.getText().toString());
		// 网点编号
		dataBusiness.setNet_code(StoFilePreference.getInstance(this)
				.getSiteCode());
		// 工号
		dataBusiness.setJob_number(StoFilePreference.getInstance(this)
				.getUserCode());

		// 蓝牙重量
		if (blueWeight > 0) {
			// 重量
			dataBusiness.setWeight(String.valueOf(blueWeight));
			blueWeight = -1;
		}

		// 插入数据
		ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
				EnumTableNames.STATUS_TABLE_SCANNING_ASSIGNPIECE);
		return ret;
	}

	/*
	 * 选择派件员
	 */
	private void selectNextStation() {
		try {
			SelectTableParcel tableParcel = new SelectTableParcel();
			if (assignPerson.getText().length() == 0) {
				tableParcel.setSelectSql(SqlSelectTableManager.SQL_STAFF_ALL);
				tableParcel.setSelectField(new String[] {});
			} else {
				tableParcel
						.setSelectSql(SqlSelectTableManager.SQL_STAFF_ONLY_LIKE);
				tableParcel.setSelectField(new String[] {
						"%"+assignPerson.getText().toString() + "%",
						"%"+assignPerson.getText().toString() + "%" });
			}
			tableParcel.setSelectCode(SALES_NUMBER);
			tableParcel.setSelectName(SALES_NAME);
			tableParcel.setProperty(null);

			Intent intent = new Intent(StoScanAssignPieceActivity.this,
					StoSelectTableActivity.class);
			intent.putExtra("tableData", tableParcel);

			startActivityForResult(intent, COURIER_RESULT);
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("selectNextStation", e.getMessage());
		}
	}

	/*
	 * 监听控件
	 */
	@SuppressLint("NewApi")
	private void initListen() {
		assignPerson.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				onBackPressed();
			}

			@Override
			public void onEditClickListener(View v) {
//				selectNextStation();
			}
		});
		findViewById(R.id.btn_select).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				selectNextStation();
			}
		});
		code.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				assignPerson.requestFocus();
				// assignPerson.setSelection(assignPerson.getText().toString()
				// .length());
			}

			@Override
			public void onEditClickListener(View v) {
				codeProcess();
				/*
				 * if (code.getText().length() <= 0) {
				 * Helper.showSoundToast(StoScanAssignPieceActivity.this,
				 * getString(R.string.code_empty), false); return; } if
				 * (!(code.getText().toString().length() ==
				 * ProcessScanCode.SCAN_LEASTCODE_LENGTH || code
				 * .getText().length() == ProcessScanCode.SCAN_MAXCODE_LENGTH))
				 * { Helper.showSoundToast(StoScanAssignPieceActivity.this,
				 * getString(R.string.code_count_error), false);
				 * code.setText(""); } else {
				 * onScanResults(code.getText().toString()); }
				 */

			}
		});

		/*
		 * code.setEditScanListener(new EditScanListener() {
		 * 
		 * @Override public void onScan() { ScanOpen(); }
		 * 
		 * @Override public void offScan() { ScanOff(); } });
		 */
		/*
		 * code.setOnClickListener(new StoOnClickListener(this) {
		 * 
		 * @Override public void mHonClick(View view) {
		 * onScanResults(code.getText().toString()); } });
		 */

		for (EditText editListener : edit) {
			/*
			 * 监听EditText内容个数
			 */
			editListener.addTextChangedListener(new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start,
						int before, int count) {
					// 控件没有内容就清空编号
					if (assignPerson.getText().toString().isEmpty()) {
						assignCode = "";
						assignName = "";
					}
				}

				@Override
				public void beforeTextChanged(CharSequence s, int start,
						int count, int after) {
				}

				@Override
				public void afterTextChanged(Editable s) {

				}
			});
		}
	}

	/**
	 * 单号逻辑处理判断
	 * 
	 * @author wxf
	 * 
	 */
	private void codeProcess() {
		String codeName = code.getText().toString();

		GetTableParcel data;
		if (codeName.length() == 0) {
			Helper.showSoundToast(this, getString(R.string.code_empty), false);
		} else {
			if (codeName.length() == RECEIVE_CODE_MAX_LENGTH) {
				codeName = codeName.substring(RECEIVE_CODE_MAX_LENGTH
						- RECEIVE_CODE_LENGTH, RECEIVE_CODE_MAX_LENGTH);
			}
			if (codeName.length() == RECEIVE_CODE_LENGTH) {
				data = queryRecvPerson(codeName);
				if (data != null) {
					assignPerson.setText(data.getSelectName());
					assignCode = data.getSelectCode();
					assignName = data.getSelectName();
				} else {
					assignName = "";
					Helper.showSoundToast(this, getString(R.string.undefined),
							false);
				}
				code.setText("");

			} else {
				onScanResults(code.getText().toString());
				/*
				 * if (CheckScanCode(code.getText().toString())) {
				 * onScanResults(code.getText().toString()); } else {
				 * code.setText(""); }
				 */
			}
		}
	}

	@Override
	public void onBackPressed() {
		// 确定退出吗?
		showNotice();
		// super.onBackPressed();

	}

	@Override
	protected void onDestroy() {
		System.out.println("StoScanActivity : StoScanAssignPieceActivity onDestroy");

		bluetoothHandler.removeMessages(BlueWeigthManager.UPDATE_BLUE_DATA);

		super.onDestroy();
	}

	@Override
	protected void handlerScanData(String scanData) {

		if(null!=filterDialog && filterDialog.isShowing()){
			return;
		}

		if (scanData != null && !scanData.equals("")) {
			String result = scanData;
			// 派件员编号
			if (result.length() == RECEIVE_CODE_MAX_LENGTH) {
				result = result.substring(RECEIVE_CODE_MAX_LENGTH
						- RECEIVE_CODE_LENGTH, RECEIVE_CODE_MAX_LENGTH);
			}
			if (result.length() == RECEIVE_CODE_LENGTH) {
				assignPerson.setText(result);
				selectNextStation();
			} else {
				EnumScanCode status = ProcessScanCode
						.getInstance(this)
						.ScanCodeResolve(
								result,
								EnumTableNames.STATUS_TABLE_SCANNING_ASSIGNPIECE);
				code.setText("");
				code.setText(result);
				code.setSelection(code.length());
				switch (status) {
				// 条码空
				case CODE_EMPTY:
					// Helper.showSoundToast(
					// StoScanAssignPieceActivity.this,
					// getString(R.string.code_empty), false);
					break;

				// 非法条码
				case CODE_ILLEGAL:
					Helper.showSoundToast(StoScanAssignPieceActivity.this,
							getString(R.string.error_code), false);
					break;
				// 成功条码
				case CODE_WAY_BILL:
					processScanData();
					break;
				default:
					break;
				}
				code.setText("");
			}
		}
	}

	/**
	 * 蓝牙连接
	 *
	 * @author wxf
	 *
	 */
	private void bluetoothConnect() {
		mBTAdapter = BluetoothAdapter.getDefaultAdapter();

		if (mBTAdapter != null) {
			if (mBTAdapter.isEnabled()) {
				weight.setText(R.string.now_connect_blue);
				blueConnecting();
			} else {
				// weight.setText(R.string.blue_no_open);
			}
		} else {
			// promptDialog(getText(R.string.blue_not_available).toString());
		}
	}

	/**
	 * 蓝牙正式连接
	 */
	private void blueConnecting() {
		String macAddress = StoFilePreference.getInstance(this)
				.getBluetoothMacAddress();
		if (!macAddress.equals("")) {
			if (blueConnectThread != null) {
				blueConnectThread.cancelDialog();
				blueConnectThread.clearBlueDevices();
				blueConnectThread = null;
			}
			// weight.setEnabled(false);
			blueConnectThread = new BlueReadThread(this, bluetoothHandler,
					macAddress, false);
			blueConnectThread.start();
		} else {
			weight.setText(R.string.select_blue_scales);
		}
	}

	private Handler bluetoothHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			Log.d("logdebug:", "msg.what:" + msg.what);
			if (msg.what == BlueWeigthManager.UPDATE_BLUE_DATA) {
				if (blueConnectThread != null) {
					blueConnectThread.cancelDialog();
				}
				if (msg.obj != null && !msg.obj.toString().equals("")) {
					String result = msg.obj.toString();
					Log.d("msg=", String.valueOf(result));
					// 表示连接蓝牙失败
					if (result.equals(BlueWeigthManager.CONNECT_FAIL)) {
						blueWeight = -1;
						if (blueConnectThread != null) {
							if (blueConnCount < 3) {
								blueConnecting();
								blueConnCount++;
								weight.setText(getText(
										R.string.blue_connect_fail).toString()
										+ ",正在重连" + blueConnCount + "...");
							} else {
								blueConnCount = 0;
								weight.setText(getText(
										R.string.blue_connect_fail).toString()
										+ ",请到系统设置, 重新设置蓝牙!");
							}
						}
					}
					// 没有选择秤型号
					else if (result
							.equals(BlueWeigthManager.NO_SELECT_SCALE_MODEL)) {
						blueWeight = -1;
						if (blueConnectThread != null) {
							weight.setText(getText(
									R.string.no_select_scales_model).toString()
									+ "请到系统设置,设置蓝牙!");

						}

					}
					// 读取数据失败
					else if (result.equals(BlueWeigthManager.READ_ERROR)) {
						blueWeight = -1;
						if (blueConnectThread != null) {
							weight.setText(R.string.get_data_error);
						}
					} else {
						// 显示重量
						blueWeight = parseFloat(result);
						weight.setText(result);
					}
				}
			}
		}

	};

}
